# coding=utf-8
import os

import arcgisscripting
import arcpy
import retry


arcpy.env.overwriteOutput = 1
arcpy.CheckOutExtension("Spatial")


@retry.retry(arcgisscripting.ExecuteError,tries=5, delay=2)
def extract(hdf_dir, NDVI_dir):
    if not os.path.exists(NDVI_dir):
        os.makedirs(NDVI_dir)
    arcpy.CheckOutExtension("Spatial")
    arcpy.env.workspace = hdf_dir
    hdfList = arcpy.ListRasters('*', 'HDF')
    for hdf in hdfList:
        Name = hdf[:-4] + ".tif"
        print Name
        # 提取波段0，对应波段与ArcGIS中显示的一致
        data = arcpy.ExtractSubDataset_management(hdf, NDVI_dir + Name, "0")
    print "OK！"


def get_hdf_dir(hdf_dir):
    hdf = os.listdir(hdf_dir)
    for i in hdf:
        if os.path.isfile(hdf_dir+i):
            hdf.remove(i)
    for i in range(len(hdf)):
        hdf[i] = hdf_dir+hdf[i]
    return hdf



if __name__ == '__main__':
    path = u"C:\\Users\\91481\\Desktop\\毕业设计\\HDF\\"
    hdf_path = get_hdf_dir(path)

    NDVI_root_path = u"C:\\Users\\91481\\Desktop\\毕业设计\\NDVI\\out\\"
    for i in range(len(hdf_path)):
        print hdf_path[i]

        try:
            extract(hdf_path[i], NDVI_root_path+hdf_path[i][-4:]+"\\")
        except arcgisscripting.ExecuteError:
            print "err"
            continue
